package com.foo.common.base.service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.foo.common.base.utils.FooUtils;
import com.foo.example.model.MyExample;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

@Service
public class GuavaCacheService {
	Logger logger = LoggerFactory.getLogger(GuavaCacheService.class);
	private LoadingCache<String, List<MyExample>> exampleCache = null;

	@SuppressWarnings("unchecked")
	public GuavaCacheService() {
		logger.info("init GuavaCacheService now");
		exampleCache = CacheBuilder.newBuilder().maximumSize(1)
				.expireAfterAccess(20, TimeUnit.SECONDS)
				.build(new CacheLoader<String, List<MyExample>>() {

					@Override
					public List<MyExample> load(String key) throws Exception {
						logger.info("reload occurred for key:{}", key);
						SessionFactory sessionFactory = FooUtils
								.getBean(SessionFactory.class);
						Session session = sessionFactory.openSession();
						List<MyExample> myList = session.createQuery(
								" from MyExample where 1=1 ").list();
						session.close();
						return myList;
					}
				});
	}

	public void put(String key, List<MyExample> value) {
		exampleCache.put(key, value);
	}

	public List<MyExample> getUnchecked(String key) {
		return exampleCache.getUnchecked(key);
	}

	public void invalidate(String key) {
		exampleCache.invalidate(key);
	}

	public static void main(String[] args) {

	}

}
